<template>
  <div class="statistics">
    <div class="box-right">
      <fire-map ref="workmap" mapHeight="100vh" :propModels="models" mapWidth="100%">
        <template #search>
          <div class="boundary-topleft">
            <el-input v-model="models.searchName" clearable suffix-icon="el-icon-search" @click.native="startSearch">
            </el-input>
          </div>
        </template>
        <template #menu>
          <div class="boundary-left">
            <data-param-menu @handleSelect="handleSelect"></data-param-menu>
          </div>
        </template>
        <template #right>
          <div class="boundary-right">
           <fire-simulation ref="fireBox" :models="models" @startDrawing="startDrawing('Polygon')"></fire-simulation>
          </div>
        </template>
        <template #bootom>
          <div class="boundary-bootom">
            <flood-info-card :models="data"></flood-info-card>
          </div>
        </template>
      </fire-map>
    </div>
    <fire-animation-layer 
      :map="mapInstance" 
      :fire-points="activeFirePoints"
    />
    <heatmap-layer 
      :map="mapInstance" 
      :heat-points="heatmapData"
    />
  </div>
</template>

<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator';
import FireMap from "@/components/FireMap.vue";
import FireSimulation from "@/views/app/components/FireSimulation.vue";
import WorkTree from "@/views/region/components/WorkTree.vue";
import DataParamMenu from '@/views/app/components/DataParamMenu.vue';
import FloodInfoCard from '@/views/app/components/FloodInfoCard.vue';

import { geoJson } from '@/api/investDataCommon';
import { searchIndex, commonInfo } from '@/api/findData';
import moment from 'moment';
import _ from 'lodash';
@Component({
  methods: {},
  components: { WorkTree, FireMap, DataParamMenu, FireSimulation, FloodInfoCard }
})
export default class fireInfo extends Vue {

  @Ref("workmap") workmap;
  @Ref("fireBox") fireBox;
  private waterLevelList: any = [];
  private mapInstance;
  private simulationTimer?: number;
  private currentFireAreas: number[][][] = [];

  private data: any = {
    disasterData: null,

  }
  debouncedHandleSearch;

  models:any = {
    spreadSpeed: 5,
    combustibleDensity: 60,
    windSpeed: 10,
    windDirection: 90, // 0-360度
    humidity: 30,
    selectedFireInfo: {
      coordinate: [] as number[],
      radius: 0,
      temperature: 0
    },
    dialogVisible: false,
    simulationTimer: null as number|null,
    fireSources: [],
  }

// 动态火点数据
get activeFirePoints() {
    return this.currentFireAreas
      .flatMap(area => this.calculateFireFront(area));
  }

  // 热力图数据
  get heatmapData() {
    return this.currentFireAreas.map(area => ({
      coord: this.getAreaCenter(area),
      intensity: this.calculateHeatIntensity(area)
    }));
  }

  // 火场前锋计算
  private calculateFireFront(area: number[][]) {
    const [minX] = area[0];
    const [maxX, maxY] = area[2];
    const points: Array<[number, number]> = [];
    
    // 生成随机火线（示例）
    for(let x=minX; x<maxX; x+=0.005) {
      points.push([x, maxY + Math.random()*0.002]);
    }
    return points;
  }

   // 火灾扩散算法（简化示例）
   private spreadFire(currentArea: number[][]) {
    // 实际应实现基于元胞自动机或物理模型的算法
    return currentArea.map(point => 
      [point[0] + Math.random()*0.01, point[1] + Math.random()*0.01]
    );
  }
  getAreaCenter(points){
    let areaSum = 0, centroidX = 0, centroidY = 0;
  for (let i = 0; i < points.length; i++) {
    const [x1, y1] = points[i];
    const [x2, y2] = points[(i+1)%points.length];
    const cross = x1*y2 - x2*y1;
    areaSum += cross;
    centroidX += (x1 + x2) * cross;
    centroidY += (y1 + y2) * cross;
  }
  areaSum /= 2;
  return [centroidX/(6*areaSum), centroidY/(6*areaSum)];
  }

  private getIntervalSpeed() {
    switch(this.models.simulationSpeed) {
      case 'slow': return 1000;
      case 'normal': return 500;
      case 'fast': return 200;
      default: return 500;
    }
  }
  // 热力强度计算
  private calculateHeatIntensity(area: number[][]) {
    const areaSize = this.calculateAreaSize(area);
    return Math.min(areaSize * 0.1, 1); // 强度系数示例
  }

  private calculateAreaSize(area: number[][]): number {
  if (!area || area.length < 3) return 0; // 非多边形直接返回0
  
  let sum = 0;
  const n = area.length;
  
  // Shoelace公式遍历计算
  for (let i = 0; i < n; i++) {
    const [x1, y1] = area[i];
    const [x2, y2] = area[(i + 1) % n]; // 自动闭合首尾点
    sum += (x1 * y2) - (x2 * y1);
  }
  
  return Math.abs(sum) / 2; // 取绝对值并除以2
}
 

  handleSelect(key, path) {
    const findIds = this.workmap.findFeature();
    if (findIds.length == 0) {
      this.$message.info("在指定区域内没有找到数据");
      return;
    }

    this.$message.success(`在指定区域内找到${findIds.length}条数据`);
    searchIndex({
      workId: this.models.workId,
      index: key,
      ids: findIds,
    }).then(res => {
      this.workmap.buildChartIndex(res.data);
    });
  }

  addFireHandler(){
    this.workmap.models.map.on('click', (event) => {
      this.$message.success("添加火源")
      console.log(event)

      const coordinate = this.workmap.models.map.getCoordinateFromPixel(event.pixel);
      this.fireBox.addFireSource(coordinate);
      this.workmap.updateFireDisplay();
    });
  }

  private simulate() {

    const floodIds = this.workmap.findFloodFeatures();

    commonInfo({
      ids: floodIds,
    }).then(res => {
      this.data.disasterData = res.data;
      const stat = {
        affectedPopulation: res.data.indexMap["1"] /10000,
        affectedArea: (this.models.area / 1000000),
        affectedCount: res.data.departInfo.length,
      };
   
      (this as any).$bus.$emit("disasterStatus", stat);
      (this as any).$bus.$emit('waterLevelListHandler', this.waterLevelList);
      const wuzichubei =  this.extractIndexData( this.data.disasterData,"0");
      (this as any).$bus.$emit("materialData", wuzichubei);
      (this as any).$bus.$emit("disasterData",  this.data.disasterData);
    });


    const floodOtherIds = this.workmap.findOtherFeatures();

    commonInfo({
      ids: floodOtherIds,
    }).then(res => {
      const wuzichubei =  this.extractIndexData( res.data,"0");
      (this as any).$bus.$emit("regionsMaterialData", wuzichubei);

      const jiuyuannengli =  this.extractIndexData( res.data,"2");
      (this as any).$bus.$emit("rescueCapability", jiuyuannengli);

    });

  }
  updateFloodArea() {
    this.workmap.updateFloodArea(this.models.waterLevel);
    this.waterLevelList.push({ value: this.models.waterLevel, time: moment(new Date()).format('yyyy-MM-DD HH:mm:ss') });
    if (this.models.area > 0) {
      (this as any).$bus.$emit('waterLevelListHandler', this.waterLevelList);
    }

  }
  reset() {
    this.workmap.reset();
    (this as any).$bus.$emit("disasterStatus", {
      affectedPopulation: 0,
      affectedArea: 0,
      affectedCount: 0,
    });
    this.waterLevelList = [];
    (this as any).$bus.$emit('waterLevelListHandler', []);
  }
  startDrawing(drawType) {

    this.workmap.startDrawing(drawType);
  }
  clearDrawing() {
    this.workmap.clearDrawing();
  }

  // 处理函数
 extractIndexData(data, index) {
  const result: Array<{
    name: string;
    count: number;    
    position:string;
    departName: string;
  }> = [];

  // 遍历部门信息
  for (const depart of data.departInfo) {
    // 获取部门名称
    const departName =data.departMap[depart.departId] || '未知部门';

    // 筛选并处理 detailList
    depart.detailList.forEach(item => {
      if (item.index === index) {
        result.push({
          name: item.codeName,
          count: item.count,
          position: item.position,
          departName
        });
      }
    });
  }

  return result;
}

  updateRadiusKm() {

    if (this.models.radiusKm >= 0 && this.models.hasWater) {

      this.workmap.createCircleByPolygonHandler();

    }
  }

  searchAddressHandler(name) {

    if (this.isLatLong(name)) {
      this.workmap.updatePosition(name.split(','))
      return;
    }
    this.workmap.searchFeature(name);

  }
  isLatLong(str) {
    const [lat, long] = str.split(',');
    if (isNaN(lat) || isNaN(long)) {
      return false;
    }
    return true;
  }

  startSearch(event) {
    if (event.target.classList.contains('el-input__icon') && this.models.searchName) {
      console.log('后缀图标被点击');
      this.searchAddressHandler(this.models.searchName);
      // 这里写你的点击逻辑
    }

  }
  created() {
    this.debouncedHandleSearch = _.debounce(this.startSearch, 1000);
    geoJson({ all: true }).then(res => {
      if (res.data.features.length > 0) {
        this.workmap.addSource(res.data);
      }
    })
  }



}
</script>
<style lang="scss" scoped>
.statistics {
  display: flex;

  .box-left {
    height: auto;
  }

  .box-right {
    flex: 1;
    padding: 0px;
    display: flex;
    flex-direction: column;
    gap: 0px;
  }
}

.boundary-topleft {
  background-color: #fff;
  position: absolute;
  padding: 10px;
  top: 30px;
  left: 18px;
  z-index: 1000;
}

.boundary-right {
  background-color: #fff;
  position: absolute;
  padding: 10px;
  top: 20px;
  right: 1px;
  z-index: 1000;
}

.boundary-bootom {
  background-color: #fff;
  position: absolute;
  padding: 10px;
  bottom: 0px;
  left: 1px;
  width: 100%;
  z-index: 1000;
}

.boundary-left {
  background-color: #fff;
  opacity: 0.8;
  position: absolute;
  padding: 10px;
  top: 100px;
  left: 1px;
  z-index: 1000;
  color: darkgreen;
}
</style>
